import React, {useEffect, useState} from 'react'
import {
  Button,
  Modal,
  List,
  InputItem,
  Toast,
  Switch
} from 'antd-mobile'
import {createForm} from 'rc-form'
import {MyNavBar} from '@/components'
import {Http} from '@/utils'
import {history, useParams} from 'umi'
import {queryString} from '@/utils'

const alert = Modal.alert

function PersonEdit(props) {
  const [ title, setTitle ] = useState('')

  const {getFieldProps, validateFields} = props.form

  const [ personInfo, setPersonInfo ] = useState({})

  const id = queryString('id')

  useEffect(() => {
    getPerson()
    if (id) {
      setTitle('修改联系人')
    } else {
      setTitle('新增联系人')
    }
  }, [])

  const handleSubmit = () => {
    validateFields(async (err, val) => {
      if (err) {
        Toast.fail('请将信息补充完整')
        return
      }
      let result=null
      if(id) {
        result = await Http({
          url: '/person/' + id, method: 'put', body: {
            name: val.name,
            No: val.No,
            isMy: val.isMy
          }
        })
      }else {
        result = await Http({
          url: '/person', method: 'post', body: {
            name: val.name,
            No: val.No,
            isMy: val.isMy
          }
        })
      }

      if (result) {
        Toast.success('修改成功')
        history.goBack()
      }
    })
  }

  const getPerson = async () => {
    if (id) {
      const result = await Http({url: '/person/' + id, method: 'get'})
      if (result) {
        setPersonInfo(result)
      }
    }
  }


  return (
    <div>
      <MyNavBar title={title}/>
      <List>
        <List>
          <InputItem {...getFieldProps('name', {
            initialValue: personInfo?.name
          })} placeholder='真实姓名'>真实姓名：</InputItem>
          <InputItem {...getFieldProps('No', {
            initialValue: personInfo?.No
          })} placeholder='身份证号'>身份证号：</InputItem>
          <List.Item
            extra={<Switch
              {...getFieldProps('isMy', {
                initialValue: personInfo?.isMy || false,
                valuePropName: 'checked'
              })}
              onClick={(checked) => {
                props.form.setFieldsValue({
                  isMy: checked
                })
              }}
            />}
          >自己</List.Item>
        </List>
        <Button type='warning' onClick={handleSubmit} style={{marginTop: '20px'}}>修改</Button>
      </List>
    </div>
  )
}

export default createForm()(PersonEdit)
